<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="listQuery" :rules="rules" :model="listQuery" :inline="true" label-position="left" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="listQuery.name" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="listQuery.code" placeholder="角色编码" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button v-waves type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter">查询</el-button>
            <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" label="序号" width="55" type="index" />
      <el-table-column align="center" label="角色名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色编码" width="180">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="数据范围" class-name="status-col" width="220">
        <template slot-scope="{row}">
          <el-tag type="danger">
            {{ row.dataScope | dataScopeFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" width="100">
        <template slot-scope="scope">
          {{ scope.row.orderNo }}
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="70">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusNameFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="160" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" header-align="center">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-dropdown style="padding: 7px" @command="(command) => handleCommand(command, row)">
            <i class="el-icon-more" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-s-operation" command="handleScopeUpdate">数据范围</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" command="handleDelete">删除角色</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称" prop="name">
              <el-input id="name" v-model="temp.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色编码" prop="code">
              <el-input id="code" v-model="temp.code" placeholder="请输入角色编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number v-model="temp.orderNo" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="temp.status">
                <el-radio :label="1">
                  启用
                </el-radio>
                <el-radio :label="2">
                  禁用
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单权限">
              <el-tree
                ref="tree"
                :check-strictly="checkStrictly"
                :data="routes"
                :props="defaultProps"
                show-checkbox
                node-key="id"
                class="permission-tree"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="授权数据范围" :visible.sync="scopeFormVisible" width="500px">
      <el-form ref="scopeForm" :rules="rules" :model="temp" label-position="left" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据范围" prop="dataScope">
              <el-select id="dataScope" v-model="temp.dataScope" class="filter-item" placeholder="请选择数据范围" style="width:100%">
                <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="scopeFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="updateScopeData">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoutes, getRoles, addRole, deleteRole, updateRole, ownMenuList, updateScope } from '@/api/role'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 1, display_name: '全部数据' },
  { key: 2, display_name: '本部门及以下数据' },
  { key: 3, display_name: '本部门数据' },
  { key: 4, display_name: '仅本人数据' },
  { key: 5, display_name: '自定义数据' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'SysRole',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = ['', 'success', 'danger']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['', '启用', '禁用']
      return statusMap[status]
    },
    dataScopeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20,
        name: undefined,
        code: undefined
      },
      calendarTypeOptions,
      temp: {
        id: undefined,
        name: '',
        code: '',
        orderNo: 100,
        status: 1,
        remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑角色',
        create: '添加角色'
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '角色编码不能为空', trigger: 'blur' }]
      },
      routes: [], // 菜单
      routesCheckedNodes: [], // 选中的菜单
      checkStrictly: false, // 在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      scopeFormVisible: false
    }
  },
  created() {
    this.getList()
    this.getRoutes()
  },
  methods: {
    getList() {
      this.listLoading = true
      getRoles(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.result.items
        this.total = response.result.total
      })
    },
    async getRoutes() {
      const res = await getRoutes()
      this.routes = res.result ?? []
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetQuery() {
      this.listQuery.name = ''
      this.listQuery.code = ''
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        remark: '',
        name: '',
        status: undefined,
        code: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.tree.setCheckedKeys([])
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.menuIdList = this.$refs.tree.getCheckedKeys()
          addRole(tempData).then(() => {
            // this.list.unshift(tempData)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增角色成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      const res = await ownMenuList(row.id)
      this.routesCheckedNodes = res.result // 获取当前角色的菜单权限
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.tree.setCheckedKeys(this.routesCheckedNodes) // 设置选中的菜单权限
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.menuIdList = this.$refs.tree.getCheckedKeys()
          updateRole(tempData).then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              message: '编辑角色成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除角色吗?', '提示信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteRole(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除角色成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleScopeUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.scopeFormVisible = true
      this.$nextTick(() => {
        this.$refs['scopeForm'].clearValidate()
      })
    },
    updateScopeData() {
      this.$refs['scopeForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateScope(tempData).then(() => {
            this.getList()
            this.scopeFormVisible = false
            this.$notify({
              message: '授权成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleCommand(command, row) {
      switch (command) {
        case 'handleScopeUpdate':
          this.handleScopeUpdate(row)
          break
        case 'handleDelete':
          this.handleDelete(row)
          break
        default:
          break
      }
    }
  }
}
</script>

<style scoped>
.filter-container .el-form-item{
    margin-bottom: auto;
}
</style>
